package im.dhc.gitdiff.util;

import java.util.regex.Pattern;

/**
 * @author songhaichao
 * @create 2020-06-04-10:19
 **/
public class FilePathFilter {

    private static final String[] SYMBOLS = {"\\", "$", "(", ")", "+", ".", "[", "]", "^", "{", "}", "|"};
    private static String[] regexs;

    static{
        try{
            PropertityUtil PropertityUtil = new PropertityUtil();
            String ignorePath = PropertityUtil.getProperty("ignore");
            String[] ignores = ignorePath.split(" ");

            regexs = new String[ignores.length];
            for(int i=0;i<ignores.length;i++){
                regexs[i] = convert(ignores[i]);
            }
        }catch(Exception e){

        }
    }

    private static String convert(String ant) {
        String regex = ant;
        for (String symbol : SYMBOLS) regex = regex.replace(symbol, '\\' + symbol);
        regex = regex.replace("?", ".{1}");
        regex = regex.replace("**/", "(.{0,}?/){0,}?");
        regex = regex.replace("**", ".{0,}?");
        regex = regex.replace("*", "[^/]{0,}?");
        while (regex.startsWith("/")) regex = regex.substring(1);
        while (regex.endsWith("/")) regex = regex.substring(0, regex.length() - 1);
        return regex;
    }

    public static boolean filterPath(String regex,String path){
        return Pattern.compile(regex).matcher(path).matches();
    }

    public static boolean filter(String path){
        for(int i=0;i<regexs.length;i++){
            if(filterPath(regexs[i],path)){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String path = "we/sdfs/sdf/ssds.ui";

        System.out.println(FilePathFilter.filter(path));

    }
}
